package com.ydDev.charateranimation;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


import Character.Character_Skeleton;
import GameTools.ydPoint;
import GameTools.ydSprite;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Gallery;

import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainView extends SurfaceView implements SurfaceHolder.Callback {

	ArrayList<ydPoint> clicked = new ArrayList<ydPoint>();
	
	ArrayList<JSONObject>frames=new ArrayList<JSONObject>();
	JSONArray jFrames=new JSONArray();
	
	int totalFrames=0;
	int currentFrame=0;

	private MainThread thread;

	private Timer myTimer;
	Boolean executeTimer = false;
	Boolean isGameState = true;

	int seconds = 0;
	
	int OFFSETY=0;

	Boolean draw;
	Paint paint;
	
	Paint textPaint;

	Character_Skeleton c1=new Character_Skeleton(new ydPoint(100, 100));
	

	int selectedPart=0;
	
	ydPoint clickedAt;

	private Boolean playing=false;

	public MainView(Context context) {
		super(context);
		clickedAt = new ydPoint(130, 500);
		// setWillNotDraw(false);

		// this.setBackgroundColor(Color.WHITE);

		getHolder().addCallback(this);
		setFocusable(true);

		thread = new MainThread(getHolder(), this);

		paint = new Paint();

		textPaint=new Paint();
		textPaint.setColor(Color.BLACK);
		
		
		init();

		myTimer = new Timer();
		myTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				// TimerMethod();
			}

		}, 0, 1000);

	}

	public void init() {
		
		c1.init();
	//	c1.setScale(0.5f);

	}

public void setSelectedPart(int i){
	selectedPart=i;
}

	@Override
	protected void onDraw(Canvas canvas) {

		super.onDraw(canvas);

		if (canvas == null) {
			return;
		}

		canvas.drawColor(Color.RED);

		 /*canvas.scale(-1f, 1f,
			        super.getWidth() * 0.5f, super.getHeight() * 0.5f);*/


		c1.draw(canvas);
		
		canvas.drawText("Total Frames: " + totalFrames, 300, 100, textPaint);
		canvas.drawText("Current Frame: " + currentFrame, 300, 110, textPaint);
		
		Log.d("DRAWING", "DRAWING");
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		clickedAt = new ydPoint((int) event.getX(), (int) event.getY());

		// clickedAt = new Point(300, 400);
		clicked.add(clickedAt);

		if(!playing){
			c1.pointTo(selectedPart, clickedAt);
		}
		
		if (isGameState) {

		}
		
		
		else{

		}
		Log.d("paint", "Circle is at: " + event.getX() + "," + event.getY());
		return true;
	}


	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		while (retry) {
			try {
				thread.join();
				retry = false;
			} catch (InterruptedException e) {
				// try again shutting down the thread
			}
		}
	}

	public void update() {
		//c1.rotatePart();
		JSONObject json=new JSONObject();
		if(playing && jFrames.length()>0 && currentFrame<jFrames.length()){
			try {
				json=(JSONObject) jFrames.get(currentFrame);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Log.d("Load JSON FRAME", json.optJSONObject(currentFrame + "").toString());
			
			c1.loadPostion(json.optJSONObject(currentFrame + ""));
			currentFrame++;
			
			if( currentFrame>=jFrames.length())
				currentFrame=0;
		}
	}


	public void setGameState(Boolean isGameState) {
		this.isGameState = isGameState;
	}

	public void saveMap(String string) {

		
	}

	public void recordClicked() {
		 JSONObject json = new JSONObject();
		 JSONObject l1 = new JSONObject();
        try {
			l1.put("head", c1.getJSONHead());
			l1.put("torso", c1.getJSONTorso());
			l1.put("rightA", c1.getJSONArm(0));
			l1.put("leftA", c1.getJSONArm(1));
			l1.put("rightL", c1.getJSONLeg(0));
			l1.put("leftL", c1.getJSONLeg(1));
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}    
        
        try {
			json.put(currentFrame+"", l1);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        Log.d("JSON_Recording", json.toString());
        frames.add(json);
        jFrames.put(json);
        currentFrame++;
        totalFrames++;
		
	}
	
	public void saveClicked(String name) throws IOException{
		//for(JSONObject f: jFrames){
			MyFiles.createFileOrAppend(name+".txt",jFrames.toString());
		//}
	}

	public void setPlaying(Boolean playing) {
		this.playing=playing;
		
		if(playing){
			currentFrame=0;
		}
		else{
			currentFrame=totalFrames;
		}
		
	}

	public void loadClicked(String name) {
		int line=0;
		String l = MyFiles.readFileLine(name + ".txt", line);
		try {
			jFrames=new JSONArray(l);
			//Log.d("Load JSON", l);
		//Log.d("Load JSON", jFrames.toString());
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*while(MyFiles.readFileLine(name, line) != null){
			String l = MyFiles.readFileLine(name, line);
			Log.d("Load JSON", line +"          " + l);
			line++;
			
		}*/
		
		return;
		
	}
	

}
